import Vue from 'vue';
import Vuex from 'vuex';
import cache from '../library/cache'
import helper from '../library/helper'
import chat from './chat'
import message from '../library/message';
Vue.use(Vuex)
export default new Vuex.Store({
    modules: {
        chat
    },
    state: {
        userinfo: {
            id: '00000',
            nickname: '请先登录',
            signature: '',
            name: ''
        },
        messages: [], //消息记录
        favorites: [] // 初始化为空数组
    },
    mutations: {
        // 添加收藏项
        ADD_FAVORITE(state, item) {
            if (!state.favorites.some(favorite => favorite.id === item.id)) {
                state.favorites.push(item);
                uni.setStorageSync('favorites', JSON.stringify(state.favorites)); // 更新缓存
            }
        },
        // 删除收藏项
        REMOVE_FAVORITE(state, itemId) {
            state.favorites = state.favorites.filter(favorite => favorite.id !== itemId);
            uni.setStorageSync('favorites', JSON.stringify(state.favorites)); // 更新缓存
        },

        // 从缓存中加载收藏项
        LOAD_FAVORITES(state) {
            const cachedFavorites = uni.getStorageSync('favorites');
            if (cachedFavorites) {
                state.favorites = JSON.parse(cachedFavorites);
            }
        },
        // 推送新的实时消息
        addMessage(state, message) {
            state.messages.push(message);
        },
        // 添加历史消息（前插历史记录）
        addHistoryMessages(state, historyMessages) {
            state.messages = [...historyMessages, ...state.messages];
        },
        DELETE_LOCAL_IMAGE(state) {
            state.messages = state.messages.splice(-2, 1);
        },
        REMOVE_LOADED_MESSAGES(state) {
            setTimeout(() => {
                state.messages = state.messages.filter(message => message.isLoaded !== true);
            }, 500); // 延迟 500ms 删除
        },
        // 更新最后一项的图片 URL
        UPDATE_LAST_MESSAGE_IMAGE(state, newImageSrc) {
            const lastMessage = state.messages[state.messages.length - 1];
            console.log('dadadadasdsdadada', lastMessage)
            if (lastMessage.message && lastMessage.message.type === 'image') {
                state.messages.unshift(...newImageSrc)
            }

        },
        clearMessages(state) {
            state.messages = []; // 清空 messages 数组
        },
        update_userinfo(state, userinfo) {
            state.userinfo = userinfo;
            uni.setStorageSync('userinfo', userinfo);
        }
    }
});